package com.sunseen.capacitormachine.modules.home;

import android.app.ProgressDialog;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sunseen.capacitormachine.CapacitorApp;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.MethodUtil;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.commumication.serialport.PlcService;
import com.sunseen.capacitormachine.commumication.serialport.bean.ChangeBatchBean;
import com.sunseen.capacitormachine.commumication.serialport.event.ChainMoveOneStepEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.CmdEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.OvenChainUpdateEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.PlcReplyEvent;
import com.sunseen.capacitormachine.commumication.serialport.event.UpdatePowerSupplyEvent;
import com.sunseen.capacitormachine.data.Constant;
import com.sunseen.capacitormachine.data.bean.HolderBean;
import com.sunseen.capacitormachine.databinding.FragmentControlBinding;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.modules.home.adapter.ChainHolderAdapter;
import com.sunseen.capacitormachine.modules.home.adapter.PowerItemAdapter;
import com.sunseen.capacitormachine.modules.home.bean.HolderAdapterBean;
import com.sunseen.capacitormachine.modules.home.bean.PowerSupplyAdapterBean;
import com.sunseen.capacitormachine.modules.home.bean.PowerSupplyBean;
import com.sunseen.capacitormachine.modules.home.event.RecoverCmdStateEvent;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.modules.parameter.bean.BatchBean;
import com.sunseen.capacitormachine.modules.parameter.bean.ProcessBean;
import com.sunseen.capacitormachine.modules.parameter.bean.ProcessParameter;
import com.sunseen.capacitormachine.modules.parameter.productivetask.adapter.BatchIdAdapter;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.ProduceStateChangeEvent;
import com.sunseen.capacitormachine.modules.permission.operation.event.IndexInitEvent;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.LayoutRes;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * @author zest
 */
public class ControlFragment extends BaseFragment {

    private static Handler countDownHandler = new Handler();

    @Override
    protected @LayoutRes
    int setLayout() {
        return R.layout.fragment_control;
    }


    private PowerItemAdapter level3Adapter;
    private PowerItemAdapter level2Adapter;
    private PowerItemAdapter level1Adapter;

    private final int cmdWaitTime = 2000;

    private int cmdState = 0;//标识当前正在发送的命令

    private Runnable cmdTimeOutRun = () -> {
        cmdState = 0;
        Toast.makeText(_mActivity, getString(R.string.wait_cmd_respond_time_out), Toast.LENGTH_SHORT).show();
    };

    private Runnable initTimeOutRun = () -> {
        cmdState = 0;
        hideProgressDialog();
        Toast.makeText(_mActivity, getString(R.string.init_cmd_respond_time_out), Toast.LENGTH_SHORT).show();
    };

    private ChainHolderAdapter testHolderAdapter;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        EventBus.getDefault().register(this);
        FragmentControlBinding binding = (FragmentControlBinding) viewDataBinding;

        binding.btnInit.setOnClickListener((view) -> {
            if (cmdState == 0) {
                cmdState = PlcService.INIT;
                EventBus.getDefault().post(new CmdEvent(PlcService.INIT));
                countDownHandler.postDelayed(initTimeOutRun, 60_000);
                //将数据库保存的上次生产使用的参数下发给各个模块
                DataUtil.sendProducingParameter();
                showProgressDialog();
            } else {
                Toast.makeText(_mActivity, getString(R.string.please_wait_cmd_finish), Toast.LENGTH_SHORT).show();
            }
        });
        binding.btnPause.setOnClickListener((view) -> {
            if (cmdState == 0) {
                cmdState = PlcService.PAUSE;
                EventBus.getDefault().post(new CmdEvent(PlcService.PAUSE));
                countDownHandler.postDelayed(cmdTimeOutRun, cmdWaitTime);

            } else {
                Toast.makeText(_mActivity, getString(R.string.please_wait_cmd_finish), Toast.LENGTH_SHORT).show();
            }
        });
        binding.btnGoOn.setOnClickListener((view) -> {
            if (cmdState == 0) {
                cmdState = PlcService.GO_ON;
                EventBus.getDefault().post(new CmdEvent(PlcService.GO_ON));
                countDownHandler.postDelayed(cmdTimeOutRun, cmdWaitTime);

            } else {
                Toast.makeText(_mActivity, getString(R.string.please_wait_cmd_finish), Toast.LENGTH_SHORT).show();
            }
        });
        binding.btnNewBatchStart.setOnClickListener((view) -> {
            if (cmdState == 0) {
                curPage = 0;
                newBatch = true;
                // 请求未生产的批号列表
                queryList(curPage, false, true);
            } else {
                Toast.makeText(_mActivity, getString(R.string.please_wait_cmd_finish), Toast.LENGTH_SHORT).show();
            }
        });
        binding.btnReplace.setOnClickListener((view) -> {
            if (cmdState == 0) {
                curPage = 0;
                newBatch = false;
                //请求未生产的批号列表
                queryList(curPage, false, false);
            } else {
                Toast.makeText(_mActivity, getString(R.string.please_wait_cmd_finish), Toast.LENGTH_SHORT).show();
            }
        });

        binding.rvLevel3.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.rvLevel2.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, true));
        binding.rvLevel1.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.rvHolder.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        initPowerSupplyData();
        level3Adapter = new PowerItemAdapter(R.layout.layout_item_control_level_2, new ArrayList<>(listLevel3));
        level2Adapter = new PowerItemAdapter(R.layout.layout_item_control_level_2, new ArrayList<>(listLevel2));
        level1Adapter = new PowerItemAdapter(R.layout.layout_item_control_level_1, new ArrayList<>(listLevel1));
        level1Adapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            startHolderListFragment((PowerSupplyAdapterBean) adapter.getData().get(position));
        });
        level2Adapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            startHolderListFragment((PowerSupplyAdapterBean) adapter.getData().get(position));
        });
        level3Adapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            startHolderListFragment((PowerSupplyAdapterBean) adapter.getData().get(position));
        });

        binding.rvLevel3.setAdapter(level3Adapter);
        binding.rvLevel2.setAdapter(level2Adapter);
        binding.rvLevel1.setAdapter(level1Adapter);

        testHolderAdapter = new ChainHolderAdapter(R.layout.layout_item_test_holder, getHolderData());
        binding.rvHolder.setAdapter(testHolderAdapter);
        testHolderAdapter.setOnItemClickListener((BaseQuickAdapter adapter, View view, int position) -> {
            ChainCapacitorListFragment fragment = new ChainCapacitorListFragment();
            HolderAdapterBean bean = (HolderAdapterBean) adapter.getData().get(position);
            fragment.setData(bean.getHolderId(), position);
            getParent().start(fragment);
        });
    }

    private void startHolderListFragment(PowerSupplyAdapterBean adapterBean) {
        HolderListFragment fragment = new HolderListFragment();
        fragment.setData(adapterBean.getNumber(), adapterBean.getVoltage(),
                adapterBean.getCurrent(), adapterBean.getStartPos(), adapterBean.getEndPos());
        getParent().start(fragment);
    }

    private List<PowerSupplyAdapterBean> listLevel1 = new ArrayList<>();
    private List<PowerSupplyAdapterBean> listLevel2 = new ArrayList<>();
    private List<PowerSupplyAdapterBean> listLevel3 = new ArrayList<>();

    private void initPowerSupplyData() {
        initLevelList(listLevel1, 0, 8);
        initLevelList(listLevel2, 9, 13);
        initLevelList(listLevel3, 14, 17);
        listLevel3.add(new PowerSupplyAdapterBean(18,
                Constant.POWER_SUPPLY_ID_GAP_TABLE[18][0],
                Constant.POWER_SUPPLY_ID_GAP_TABLE[18][1]));
    }

    private void initLevelList(List<PowerSupplyAdapterBean> list, int startPos, int endPos) {
        for (int i = startPos; i <= endPos; i++) {
            list.add(new PowerSupplyAdapterBean(i + 1,
                    Constant.POWER_SUPPLY_ID_GAP_TABLE[i][0],
                    Constant.POWER_SUPPLY_ID_GAP_TABLE[i][1]));
        }
    }

    private List<HolderAdapterBean> getHolderData() {
        final ArrayList<HolderAdapterBean> chainHolderList = new ArrayList<>();
        for (int i = 0, size = DataUtil.chainHolderList.size(); i < size; i++) {
            final HolderBean holderBean = DataUtil.chainHolderList.get(i);
            chainHolderList.add(new HolderAdapterBean(holderBean.getHolderId(), i, true));
        }
        return chainHolderList;
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPlcReplyEvent(PlcReplyEvent event) {
        Log.e("PlcService ", cmdState + ", " + event.isInit());
        if (event.isInit()) {
            countDownHandler.removeCallbacks(initTimeOutRun);
            hideProgressDialog();
            Toast.makeText(_mActivity, getString(R.string.init_finished), Toast.LENGTH_SHORT).show();
        } else {
            if (cmdState != 1) {
                countDownHandler.removeCallbacks(cmdTimeOutRun);
                Log.e("PlcService", "   cmdTimeOutRun");
                switch (cmdState) {
                    case PlcService.PAUSE: {
                        DataUtil.setProduceState(DataUtil.ProducePause);
                    }
                    break;
                    case PlcService.GO_ON: {
                        DataUtil.setProduceState(DataUtil.Producing);
                    }
                    break;
                    case PlcService.START: {
                        DataUtil.setProduceState(DataUtil.Producing);
                        Toast.makeText(_mActivity, "该批次参数下发成功", Toast.LENGTH_SHORT).show();
                        if (popupWindow != null) {
                            if (popupWindow.isShowing()) {
                                if (cancelBtn != null) {
                                    cancelBtn.performClick();
                                }
                            }
                        }
                    }
                    break;
                    case PlcService.REPLACE: {
                        DataUtil.setProduceState(DataUtil.Producing);
                        /**
                         * 换料命令发送成功，将此烤箱内最后一颗电容的uid加入记录一批电容最后一颗电容的列表中
                         * */
                        if(!TextUtils.isEmpty(DataUtil.ovenLastCapacitorUid)){
                            DataUtil.lastCapacitorUidQueue.add(DataUtil.ovenLastCapacitorUid);
                        }
                        Toast.makeText(_mActivity, "换料参数下发成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                    case PlcService.RESET: {

                    }
                    break;
                }
                //EventBus.getDefault().post(new ProduceStateChangeEvent());
            }
        }
        cmdState = 0;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecoverCmdState(RecoverCmdStateEvent event) {
        if (event.isDelayRun()) {
            countDownHandler.postDelayed(cmdTimeOutRun, cmdWaitTime);
        } else {
            cmdState = 0;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateVoltage(UpdatePowerSupplyEvent event) {
        PowerSupplyAdapterBean adapterBean;
        PowerSupplyBean powerSupplyBean;
        for (int i = 0; i < 9; i++) {
            powerSupplyBean = event.getSupplyBeanList().get(i);
            adapterBean = listLevel1.get(i);
            adapterBean.setVoltage(powerSupplyBean.getVoltage());
            adapterBean.setCurrent(powerSupplyBean.getCurrent());
            adapterBean.setNormal(powerSupplyBean.getState() < 0b00000100);
        }
        level1Adapter.setNewData(new ArrayList<>(listLevel1));

        for (int i = 9; i < 14; i++) {
            powerSupplyBean = event.getSupplyBeanList().get(i);
            adapterBean = listLevel2.get(i - 9);
            adapterBean.setVoltage(powerSupplyBean.getVoltage());
            adapterBean.setCurrent(powerSupplyBean.getCurrent());
            adapterBean.setNormal(powerSupplyBean.getState() < 0b00000100);
        }
        level2Adapter.setNewData(new ArrayList<>(listLevel2));

        for (int i = 14; i < 18; i++) {
            powerSupplyBean = event.getSupplyBeanList().get(i);
            adapterBean = listLevel3.get(i - 14);
            adapterBean.setVoltage(powerSupplyBean.getVoltage());
            adapterBean.setCurrent(powerSupplyBean.getCurrent());
            adapterBean.setNormal(powerSupplyBean.getState() < 0b00000100);
        }
        adapterBean = listLevel3.get(4);
        powerSupplyBean = event.getSupplyBeanList().get(17);
        adapterBean.setVoltage(powerSupplyBean.getVoltage());
        adapterBean.setCurrent(powerSupplyBean.getCurrent());
        adapterBean.setNormal(powerSupplyBean.getState() < 0b00000100);

        level3Adapter.setNewData(new ArrayList<>(listLevel3));
    }

    private ProgressDialog progressDialog;

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getContext());
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
            progressDialog.setContentView(R.layout.layout_init_progress_dialog);
        } else {
            progressDialog.show();
        }
    }

    private void hideProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void onChainMoveOneStep(ChainMoveOneStepEvent event) {
        if (DataUtil.getProduceState() != DataUtil.Producing) {
            DataUtil.setProduceState(DataUtil.Producing);
            EventBus.getDefault().post(new ProduceStateChangeEvent());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOvenChainUpdate(OvenChainUpdateEvent event) {
        testHolderAdapter.setNewData(getHolderData());
    }


    private int curPage = 0;
    private boolean newBatch = true;
    private String batchId;

    private PopupWindow popupWindow;
    private BatchIdAdapter adapter;
    private Toolbar toolbar;
    private TextView batchIdTv;

    private Button cancelBtn;

    private void initPopupWindow() {
        popupWindow = new PopupWindow(_mActivity);
        View popupView = LayoutInflater.from(_mActivity).inflate(R.layout.layout_popup_parameter_choose, null);
        popupWindow.setContentView(popupView);
        popupWindow.setWidth(1120);
        popupWindow.setHeight(720);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.cb_bg_gray_light));
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(false);
        popupWindow.update();
        popupWindow.setOnDismissListener(() -> {
            batchIdTv.setText(R.string.choose_batch_tip);
            batchId = null;
        });
        toolbar = popupView.findViewById(R.id.parameter_toolbar);
        batchIdTv = popupView.findViewById(R.id.batch_id_tv);
        RecyclerView batchIdRv = popupView.findViewById(R.id.batch_rv);
        batchIdRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        adapter = new BatchIdAdapter(R.layout.layout_item_batch_browse);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            BatchBean batchBean = (BatchBean) adapter.getData().get(position);
            batchId = batchBean.getBatchId();
            batchIdTv.setText(String.format(getString(R.string.batch_selected_tip_format), batchId));
        });
        batchIdRv.setAdapter(adapter);
        cancelBtn = popupView.findViewById(R.id.hide_btn);
        cancelBtn.setOnClickListener((v) -> {
            batchId = null;
            toolbar.setTitle(getString(R.string.choose_batch_tip));
            popupWindow.dismiss();
        });
        Button confirmBtn = popupView.findViewById(R.id.confirm_btn);
        confirmBtn.setOnClickListener((v) -> {
//            Log.e("xiaochunhui","size = " + CapacitorApp.getList().size());
//            if(CapacitorApp.getList().size() < 6){
                if (batchId != null) {
                    cmdState = newBatch ? PlcService.START : PlcService.REPLACE;
                    queryProcessParameter(newBatch, batchId);
                    countDownHandler.postDelayed(cmdTimeOutRun, 5000);
                } else {
                    Toast.makeText(getContext(), R.string.choose_batch_tip, Toast.LENGTH_SHORT).show();
                }
//            } else {
//                Toast.makeText(getContext(), R.string.the_queue_is_full, Toast.LENGTH_SHORT).show();
//            }
        });
    }

    private View fragmentRootView;

    private void showPopupWindow(boolean newBatch) {
        if (popupWindow == null) {
            initPopupWindow();
            fragmentRootView = LayoutInflater.from(_mActivity).inflate(R.layout.fragment_control, null);
        }
        if (newBatch) {
            toolbar.setTitle(R.string.choose_new_batch_tip);
        } else {
            toolbar.setTitle(R.string.choose_replace_batch_tip);
        }
        popupWindow.showAsDropDown(fragmentRootView, 300, 68, Gravity.CENTER);
    }

    /**
     * 请求批次号列表
     *
     * @param page    请求的列表的页码 (每页数据默认10条)
     * @param addLast true:往列表后面添加， false:刷新列表
     */
    private void queryList(int page, boolean addLast, boolean newBatch) {
        RestClient.builder()
                .url(HttpUtil.Process)
                .params("status", 0)
                .params("page", page)
                .success((String response) -> {
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null) {
                        if (rootObj.getIntValue("status") == 1) {
                            JSONObject dataObj = rootObj.getJSONObject("data");
                            if (dataObj != null) {
                                JSONObject listObj = dataObj.getJSONObject("list");
                                if (listObj != null) {
                                    List<BatchBean> list = JSON.parseArray(listObj.getJSONArray("data").toJSONString(), BatchBean.class);
                                    if (list != null) {
                                        if (list.size() > 0) {
                                            curPage = listObj.getIntValue("current_page");
                                            Log.e("test", "list.size = " + list.size());
                                            if (addLast) {
                                                adapter.addData(list);
                                            } else {
                                                showPopupWindow(newBatch);
                                                adapter.setNewData(list);
                                            }
                                            adapter.loadMoreComplete();
                                        } else {

                                            if (curPage == 0) {
                                                //服务器中无数据
                                                Toast.makeText(_mActivity, "后台无相关数据", Toast.LENGTH_SHORT).show();
                                            } else {
                                                //已加载到最后一页
                                                adapter.setEnableLoadMore(false);
                                            }
                                        }
                                    } else {
                                        Toast.makeText(_mActivity, "请求结果为空: ", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    Toast.makeText(_mActivity, "请求结果为空: ", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                Toast.makeText(_mActivity, "请求结果为空: ", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知原因";
                            }
                            Toast.makeText(_mActivity, "请求结果为空: " + msg, Toast.LENGTH_SHORT).show();
                            Log.e("test", msg);
                        }
                    } else {
                        Toast.makeText(_mActivity, "请求结果为空", Toast.LENGTH_SHORT).show();
                    }
                })
                .failure(() -> {
                    Log.e("test", "待生产批号列表请求失败");
                    Toast.makeText(_mActivity, "待生产批号列表请求失败", Toast.LENGTH_SHORT).show();
                })
                .error((int code, String msg) -> {
                    Log.e("test", "待生产批号列表请求错误 " + code + " " + msg);
                    Toast.makeText(_mActivity, "待生产批号列表请求错误: " + msg, Toast.LENGTH_SHORT).show();
                })
                .build()
                .get();
    }

    private void queryProcessParameter(final boolean newBatch, final String batchId) {
        RestClient.builder()
                .url(HttpUtil.Process + "/" + batchId)
                .params("deviceNo", DataUtil.DeviceNo)
                .success((String response) -> {
                    JSONObject rootObj = JSON.parseObject(response);
                    if (rootObj != null) {
                        int status = rootObj.getIntValue("status");
                        if (status == 1) {
                            JSONObject dataObj = rootObj.getJSONObject("data");
                            if (dataObj != null) {
                                ProcessBean bean = JSON.parseObject(
                                        dataObj.getJSONObject("item").toJSONString(),
                                        ProcessBean.class);
                                if (bean != null) {
                                    sendParameter(bean, newBatch);
//                                    boolean isAdd = true;
                                    MethodUtil.updateBatchProduceStatus(bean.getBatchId(), 1);
//                                    for (int i = 0; i < CapacitorApp.getList().size(); i ++) {
//                                        if(bean.getBatchId().equals(CapacitorApp.getList().get(i).getBatchid())){
//                                            isAdd = false;
//                                        }
//                                    }
//                                    if (isAdd){
//                                        CapacitorApp.getList().add(new ChangeBatchBean(bean.getBatchId(),-1));//启动生产
//                                    }
                                } else {
                                    Toast.makeText(_mActivity, "工艺参数查询结果为空", Toast.LENGTH_SHORT).show();
                                    Log.e("test", "工艺参数查询结果为空");
                                }
                            } else {
                                Toast.makeText(_mActivity, "工艺参数查询结果为空", Toast.LENGTH_SHORT).show();
                                Log.e("test", "工艺参数查询结果为空:");
                            }
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知原因";
                            }
                            Toast.makeText(_mActivity, "工艺参数查询失败: " + msg, Toast.LENGTH_SHORT).show();
                            Log.e("test", "工艺参数查询失败: " + msg);
                        }
                    } else {
                        Toast.makeText(_mActivity, "工艺参数查询失败", Toast.LENGTH_SHORT).show();
                        Log.e("test", "工艺参数查询失败,根数据为空");
                    }
                })
                .failure(() -> {
                    Toast.makeText(_mActivity, "工艺参数查询结果失败", Toast.LENGTH_SHORT).show();
                    Log.e("test", "工艺参数查询结果失败");
                })
                .error((int code, String msg) -> {
                    Toast.makeText(_mActivity, "工艺参数查询结果错误", Toast.LENGTH_SHORT).show();
                    Log.e("test", "工艺参数查询结果错误 " + code + " " + msg);
                })
                .build()
                .get();
    }

    private void sendParameter(ProcessBean processBean, final boolean newBatch) {
        ProcessParameter processParameter = new ProcessParameter();
        processParameter.setBatchId(processBean.getBatchId());
        processParameter.setPowerV1(string2Int(processBean.getV1()));
        processParameter.setPowerI1(string2Int(processBean.getI1()));
        processParameter.setPowerV2(string2Int(processBean.getV2()));
        processParameter.setPowerI2(string2Int(processBean.getI2()));
        processParameter.setPowerV3(string2Int(processBean.getV3()));
        processParameter.setPowerI3(string2Int(processBean.getI3()));
        processParameter.setPowerV4(string2Int(processBean.getV4()));
        processParameter.setPowerI4(string2Int(processBean.getI4()));
        processParameter.setPowerV5(string2Int(processBean.getV5()));
        processParameter.setPowerI5(string2Int(processBean.getI5()));
        processParameter.setPowerV6(string2Int(processBean.getV6()));
        processParameter.setPowerI6(string2Int(processBean.getI6()));
        processParameter.setPowerV7(string2Int(processBean.getV7()));
        processParameter.setPowerI7(string2Int(processBean.getI7()));
        processParameter.setPowerV8(string2Int(processBean.getV8()));
        processParameter.setPowerI8(string2Int(processBean.getI8()));
        processParameter.setPowerV9(string2Int(processBean.getV9()));
        processParameter.setPowerI9(string2Int(processBean.getI9()));
        processParameter.setPowerV10(string2Int(processBean.getV10()));
        processParameter.setPowerI10(string2Int(processBean.getI10()));
        processParameter.setPowerV11(string2Int(processBean.getV11()));
        processParameter.setPowerI11(string2Int(processBean.getI11()));
        processParameter.setPowerV12(string2Int(processBean.getV12()));
        processParameter.setPowerI12(string2Int(processBean.getI12()));
        processParameter.setPowerV13(string2Int(processBean.getV13()));
        processParameter.setPowerI13(string2Int(processBean.getI13()));
        processParameter.setPowerV14(string2Int(processBean.getV14()));
        processParameter.setPowerI14(string2Int(processBean.getI14()));
        processParameter.setPowerV15(string2Int(processBean.getV15()));
        processParameter.setPowerI15(string2Int(processBean.getI15()));
        processParameter.setPowerV16(string2Int(processBean.getV16()));
        processParameter.setPowerI16(string2Int(processBean.getI16()));
        processParameter.setPowerV17(string2Int(processBean.getV17()));
        processParameter.setPowerI17(string2Int(processBean.getI17()));
        processParameter.setPowerV18(string2Int(processBean.getV18()));
        processParameter.setPowerI18(string2Int(processBean.getI18()));
        processParameter.setChargeV(string2Int(processBean.getChargeV()));
        processParameter.setChargeI(string2Int(processBean.getChargeI()));
        processParameter.setSurgeV(string2Int(processBean.getSurgeV()));
        processParameter.setSurgeI(string2Int(processBean.getSurgeI()));
        processParameter.setTestV(string2Int(processBean.getTestV()));
        processParameter.setTestI(string2Int(processBean.getTestI()));
        processParameter.setShortCircuitV(string2Int(processBean.getShortCircuitV()));
        processParameter.setOpenCircuitV(string2Int(processBean.getOpenCircuitV()));
        processParameter.setLeakageUpperLimit(string2Int(processBean.getLeakageUpperLimit()));
        processParameter.setLeakageLowerLimit(string2Int(processBean.getLeakageLowerLimit()));
        processParameter.setLeakageMiddleLimit(string2Int(processBean.getLeakageMiddleLimit()));
        processParameter.setCapacitorNominal(string2Float(processBean.getCapacitorNominal()));
        processParameter.setPremiumLimit(string2Float(processBean.getPremiumLimit()));
        processParameter.setSuperiorLowerLimit(string2Float(processBean.getSuperiorLowerLimit()));
        processParameter.setGoodProductUpperLimit(string2Float(processBean.getGoodProductUpperLimit()));
        processParameter.setGoodProductLowerLimit(string2Float(processBean.getGoodProductLowerLimit()));
        processParameter.setGoodProduct2UpperLimit(string2Float(processBean.getGoodProduct2UpperLimit()));
        processParameter.setGoodProduct2LowerLimit(string2Float(processBean.getGoodProduct2LowerLimit()));
        processParameter.setUnAgedVoltage(string2Int(processBean.getUnAgedVoltage()));
        processParameter.setLossAngelUpperLimit(string2Int(processBean.getLossAngelUpperLimit()));
        processParameter.setUpperImpedanceLimit(string2Int(processBean.getUpperImpedanceLimit()));
        processParameter.setAgingTime(string2Int(processBean.getAgingTime()));
        processParameter.setCodingMark(processBean.getCodingMark());
        processParameter.setCodingStartNumber(processBean.getCodingStartNumber());
        processParameter.setSurgeUpperLimit(string2Int(processBean.getSurgeUpperLimit()));
        processParameter.setUpperTemperatureLimit(string2Int(processBean.getUpperTemperatureLimit()));
        processParameter.setInstrumentFrequency(120);
        processParameter.setOvenTemperature(string2Int(processBean.getOvenTemperature()));
        //Log.e("xiaochunhui:", " processBean = " + string2Int(processBean.getImplosionTime()) + "");
        processParameter.setImplosionTime(string2Int(processBean.getImplosionTime()));
        processParameter.setImplosionVoltageUpperLimit(string2Int(processBean.getImplosionVoltageUpperLimit()));
        processParameter.setImplosionVoltageLowerLimit(string2Int(processBean.getImplosionVoltageLowerLimit()));
        processParameter.setImplosionCurrentLowerLimit(string2Int(processBean.getImplosionCurrentLowerLimit()));
        processParameter.setImplosionCurrentUpperLimit(string2Int(processBean.getImplosionCurrentUpperLimit()));
        processParameter.setFeedInTableHeight(string2Int(processBean.getFeedInTableHeight()));
        processParameter.setFeedInAngle(string2Int(processBean.getFeedInAngle()));
        processParameter.setDischargeTableHeight(string2Int(processBean.getDischargeTableHeight()));
        processParameter.setDischargeAngle(string2Int(processBean.getDischargeAngle()));
        DataUtil.producingParameter.setBatchId(processBean.getBatchId());
        DataUtil.producingParameter.setImplosionLowerLimitCurrent(
                processParameter.getImplosionCurrentLowerLimit());
        DataUtil.producingParameter.setImplosionUpperLimitCurrent(
                processParameter.getImplosionCurrentUpperLimit());
        DataUtil.producingParameter.setImplosionLowerLimitVoltage(
                processParameter.getImplosionVoltageLowerLimit());
        DataUtil.producingParameter.setImplosionUpperLimitVoltage(
                processParameter.getImplosionVoltageUpperLimit());
        //Log.e("xiaochunhui:", " processParameter = " + processParameter.getImplosionTime() + "");
        DataUtil.producingParameter.setImplosionTime(processParameter.getImplosionTime());
        //Log.e("xiaochunhui:", " producingParameter = " + DataUtil.producingParameter.getImplosionTime() + "");
        float surgeUpperLimit = processParameter.getSurgeUpperLimit() / 10f;
        DataUtil.producingParameter.setSurgeUpperLimitVoltage((int) surgeUpperLimit);
        DataUtil.saveProducingParameter();
        DataUtil.sendProducingParameter();
        if (newBatch) {
            EventBus.getDefault().post(new CmdEvent(PlcService.START, processParameter));
        } else {
            EventBus.getDefault().post(new CmdEvent(PlcService.REPLACE, processParameter));
        }
        if(!DataUtil.FlowCardBatchId.equals(processParameter.getBatchId())){
            if(DataUtil.DefaultBatchId.equals(DataUtil.FlowCardBatchId)){
                DataUtil.FlowCardBatchIdProducing = processParameter.getBatchId();//在刚开机第一次生产时，生产中是没有单号的
            }
            DataUtil.FlowCardBatchId = processParameter.getBatchId();//下发新的参数，将单号保存在此处，在下发换料回复后将值赋值给FlowCardBatchIdProducing
        }
    }

    private int string2Int(String str) {
        try {
            return Integer.valueOf(str);
        } catch (NumberFormatException e) {
            return 0;
        }
    }


    private float string2Float(String str) {
        try {
            return Integer.parseInt(str) / 10f;
        } catch (NumberFormatException e) {
            return 0;
        }
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onIndexInit(IndexInitEvent event) {
        testHolderAdapter.setNewData(getHolderData());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
